package com.group3.merchant.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.group3.entity.Merchant;
import com.group3.merchant.dao.IMerchantDao;
import com.group3.merchant.utils.DbUtils;

public class MerchantDaoImpl implements IMerchantDao {

	@Override
	public Merchant insertMerchant(Merchant merchant) {
		String sql = "insert into merchant values (?,?,?,?,?,?)";
		Connection conn = DbUtils.getConnection();
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, merchant.getmId());
			ps.setString(2, merchant.getmName());
			ps.setString(3, merchant.getPassword());
			ps.setString(4, merchant.getAddress());
			ps.setString(5, merchant.getImageUrl());
			ps.setString(6, merchant.getIdCardUrl());
			int line = ps.executeUpdate();
			if (line != 0) {
				return merchant;
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DbUtils.free(conn, ps, null);
		}
		return null;
	}

	@Override
	public Merchant login(String name, String password) {
		String sql = "select * from merchant where m_name =? and m_password=?";
		Connection conn = DbUtils.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Merchant merch = null;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, name);
			ps.setString(2, password);
			rs = ps.executeQuery();
			while (rs.next()) {
				merch = new Merchant();
				merch.setmId(rs.getString(1));
				merch.setmName(rs.getString(2));
				merch.setPassword(rs.getString(3));
				merch.setAddress(rs.getString(4));
				merch.setImageUrl(rs.getString(5));
				merch.setIdCardUrl(rs.getString(6));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.free(conn, ps, rs);
		}
		return merch;
	}

	@Override
	public Merchant update(Merchant merchant) {
		String sql = "update merchant set m_name=?,m_password=?,m_address=?,m_imageurl=?,m_idcardurl=? where m_id = ?";
		Connection conn = DbUtils.getConnection();
		PreparedStatement ps = null;
		int lines = 0;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, merchant.getmName());
			ps.setString(2, merchant.getPassword());
			ps.setString(3, merchant.getAddress());
			ps.setString(4, merchant.getImageUrl());
			ps.setString(5, merchant.getIdCardUrl());
			ps.setString(6, merchant.getmId());
			lines = ps.executeUpdate();
			if (lines == 1) {
				return merchant;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtils.free(conn, ps, null);
		}
		return null;
	}

}
